package com.example.backend.controller;

import com.example.backend.domain.entity.Ticket;
import com.example.backend.domain.entity.User;
import com.example.backend.domain.enums.TicketStatus;
import com.example.backend.domain.enums.TicketPriority;
import com.example.backend.dto.ApiResponse;
import com.example.backend.dto.PageResponse;
import com.example.backend.dto.TicketFilter;
import com.example.backend.dto.TicketDto;
// import com.example.backend.dto.BatchAssignRequest; // 临时禁用
// import com.example.backend.dto.BatchStatusRequest; // 临时禁用
// import com.example.backend.dto.BatchDeleteRequest; // 临时禁用
// import com.example.backend.dto.BatchResult; // 临时禁用
import com.example.backend.mapper.SimpleMappers;
import com.example.backend.constants.RoleConstants;
import com.example.backend.security.RequirePermission;
import com.example.backend.service.TicketService;
import com.example.backend.service.UserService;
import com.example.backend.util.CurrentUserService;
// import com.example.backend.service.BatchOperationService; // 临时禁用
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.format.annotation.DateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Instant;
import java.util.List;

@RestController
@RequestMapping("/api/tickets")
@Tag(name = "工单管理", description = "工单的增删改查操作")
@SecurityRequirement(name = "Bearer Authentication")
public class TicketController {
    
    private static final Logger log = LoggerFactory.getLogger(TicketController.class);
    
    private final TicketService ticketService;
    private final UserService userService;
    private final CurrentUserService currentUserService;
    // private final BatchOperationService batchOperationService; // 临时禁用

    public TicketController(TicketService ticketService, UserService userService, CurrentUserService currentUserService) {
        this.ticketService = ticketService;
        this.userService = userService;
        this.currentUserService = currentUserService;
        // this.batchOperationService = batchOperationService; // 临时禁用
    }

    /**
     * 创建工单请求
     * 注意：creatorId 和 customerId 已废弃，系统将自动从当前登录用户获取
     */
    public record CreateTicketRequest(
            @NotBlank @Size(max = 200) String title,
            @NotBlank @Size(max = 2000) String description,
            String descriptionDetail,
            Long categoryId,
            TicketPriority priority) {}

    public record UpdateStatusRequest(
            TicketStatus status,
            String note) {}

    public record AssignTicketRequest(
            Long assigneeId) {}

    public record UpdatePriorityRequest(
            TicketPriority priority) {}

    @PostMapping
    @Operation(summary = "创建工单", description = "创建一个新的工单")
    @RequirePermission(roles = {RoleConstants.CUSTOMER, RoleConstants.AGENT, RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<TicketDto>> create(@Valid @RequestBody CreateTicketRequest req) {
        String requestId = "CTRL-" + System.currentTimeMillis();
        
        try {
            log.info("╔═══════════════════════════════════════════════════════════════");
            log.info("║ [{}] 收到创建工单请求", requestId);
            log.info("╠═══════════════════════════════════════════════════════════════");
            log.info("║ [{}] 请求参数详情:", requestId);
            log.info("║   - 标题: {}", req.title());
            log.info("║   - 描述: {}", req.description());
            log.info("║   - 详细描述: {}", req.descriptionDetail());
            log.info("║   - 分类ID: {}", req.categoryId());
            log.info("║   - 优先级: {}", req.priority());
            log.info("╚═══════════════════════════════════════════════════════════════");
            
            // 【安全修复】从 SecurityContext 获取当前登录用户
            // 不再信任前端传递的用户ID，完全由后端控制用户身份
            log.info("[{}] 步骤1: 从 SecurityContext 获取当前登录用户", requestId);
            
            User currentUser;
            try {
                currentUser = currentUserService.getCurrentUser();
                log.info("[{}] ✅ 成功获取当前用户", requestId);
            } catch (Exception e) {
                log.error("[{}] ❌ 获取当前用户失败: {}", requestId, e.getMessage(), e);
                return ResponseEntity.status(401).body(
                    ApiResponse.error("用户认证失败，请重新登录")
                );
            }
            
            if (currentUser == null) {
                log.error("[{}] ❌ 当前用户为 null", requestId);
                return ResponseEntity.status(401).body(
                    ApiResponse.error("用户认证信息无效，请重新登录")
                );
            }
            
            log.info("[{}] ✅ 当前登录用户: id={}, username={}, role={}", 
                requestId, currentUser.getId(), currentUser.getUsername(), currentUser.getRole());
            
            // 创建者和客户都是当前登录用户
            User creator = currentUser;
            User customer = currentUser;
            
            log.info("[{}] ✅ 工单创建者: {} (ID: {})", 
                requestId, creator.getUsername(), creator.getId());
            log.info("[{}] ✅ 工单客户: {} (ID: {})", 
                requestId, customer.getUsername(), customer.getId());
            
            // 验证分类ID（如果提供）
            if (req.categoryId() != null) {
                log.info("[{}] 步骤2: 验证分类ID: {}", requestId, req.categoryId());
                // TODO: 添加分类验证逻辑
                log.info("[{}] ⚠️  分类验证跳过（待实现）", requestId);
            }
            
            // 构建工单实体
            log.info("[{}] 步骤3: 构建工单实体", requestId);
            Ticket ticket = Ticket.builder()
                    .title(req.title())
                    .description(req.description())
                    .descriptionDetail(req.descriptionDetail())
                    .priority(req.priority() != null ? req.priority() : TicketPriority.MEDIUM)
                    .createdBy(creator)
                    .customer(customer)
                    .build();
            
            log.info("[{}] ✅ 工单实体构建完成:", requestId);
            log.info("[{}]    - 标题: {}", requestId, ticket.getTitle());
            log.info("[{}]    - 优先级: {}", requestId, ticket.getPriority());
            log.info("[{}]    - 创建者: {}", requestId, ticket.getCreatedBy().getUsername());
            log.info("[{}]    - 客户: {}", requestId, ticket.getCustomer().getUsername());
            
            // 调用服务层保存
            log.info("[{}] 步骤4: 调用 ticketService.create() 保存工单", requestId);
            Ticket saved = ticketService.create(ticket, creator);
            
            log.info("╔═══════════════════════════════════════════════════════════════");
            log.info("║ [{}] ✅ 工单保存成功！", requestId);
            log.info("╠═══════════════════════════════════════════════════════════════");
            log.info("║   - 工单ID: {}", saved.getId());
            log.info("║   - 工单编号: {}", saved.getTicketNumber());
            log.info("║   - 状态: {}", saved.getStatus());
            log.info("║   - 创建者ID: {}", saved.getCreatedBy().getId());
            log.info("║   - 客户ID: {}", saved.getCustomer().getId());
            log.info("║   - 创建时间: {}", saved.getCreatedAt());
            log.info("╚═══════════════════════════════════════════════════════════════");
            
            // 转换为DTO
            TicketDto dto = SimpleMappers.toTicketDto(saved);
            log.info("[{}] ✅ DTO转换完成，准备返回响应", requestId);
            
            return ResponseEntity.ok(ApiResponse.success("工单创建成功", dto));
            
        } catch (Exception e) {
            log.error("╔═══════════════════════════════════════════════════════════════");
            log.error("║ [{}] ❌ 创建工单失败！", requestId);
            log.error("╠═══════════════════════════════════════════════════════════════");
            log.error("║   - 异常类型: {}", e.getClass().getName());
            log.error("║   - 异常消息: {}", e.getMessage());
            log.error("║   - 请求参数: categoryId={}, title={}", 
                req.categoryId(), req.title());
            log.error("╚═══════════════════════════════════════════════════════════════");
            log.error("[{}] 异常堆栈:", requestId, e);
            
            // 不吞掉异常，保留完整的错误信息
            return ResponseEntity.badRequest().body(
                ApiResponse.error("创建工单失败: " + e.getMessage())
            );
        }
    }

    @GetMapping
    @Operation(summary = "获取工单列表", description = "分页获取所有工单，支持多条件过滤与排序（带数据权限过滤）")
    @RequirePermission(roles = {RoleConstants.CUSTOMER, RoleConstants.AGENT, RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<PageResponse<TicketDto>>> list(
            TicketFilter filter,
            Pageable pageable) {
        try {
            User currentUser = currentUserService.getCurrentUser();
            
            // 根据TicketFilter中的排序参数构建Pageable
            Pageable finalPageable = buildPageableFromFilter(filter, pageable);
            
            Page<TicketDto> page = ticketService.list(filter, finalPageable, currentUser)
                    .map(SimpleMappers::toTicketDto);

            // 管理员空数据特殊提示
            if (currentUser.getRole() == com.example.backend.domain.enums.Role.ADMIN && page.getTotalElements() == 0) {
                log.warn("【管理员空工单列表告警】当前管理员({}), 查询工单列表结果为空，请检查数据或登录态！", currentUser.getUsername());
                return ResponseEntity.ok(ApiResponse.success(
                    "系统管理员: 当前工单列表为空。如果数据库确实有工单且角色为ADMIN，请检查用户账号、数据权限、中间件缓存、数据库等问题。",
                    PageResponse.of(page)
                ));
            }
            return ResponseEntity.ok(ApiResponse.success(PageResponse.of(page)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取工单列表失败: " + e.getMessage()));
        }
    }
    
    /**
     * 根据TicketFilter中的排序参数构建Pageable对象
     */
    private Pageable buildPageableFromFilter(TicketFilter filter, Pageable originalPageable) {
        // 使用filter中的分页参数，如果没有则使用原始pageable的参数
        int page = filter.getPage() != null ? filter.getPage() : originalPageable.getPageNumber();
        int size = filter.getSize() != null ? filter.getSize() : originalPageable.getPageSize();
        
        // 构建排序
        Sort sort;
        if (filter.getSortBy() != null && !filter.getSortBy().trim().isEmpty()) {
            Sort.Direction direction = "ASC".equalsIgnoreCase(filter.getSortDirection()) ? 
                Sort.Direction.ASC : Sort.Direction.DESC;
            sort = Sort.by(direction, filter.getSortBy());
        } else {
            // 使用原始pageable的排序，如果没有则使用默认排序
            sort = originalPageable.getSort().isSorted() ? 
                originalPageable.getSort() : 
                Sort.by(Sort.Direction.DESC, "createdAt");
        }
        
        return PageRequest.of(page, size, sort);
    }

    @GetMapping("/search")
    @Operation(summary = "搜索工单", description = "根据关键词搜索工单（带数据权限过滤）")
    public ResponseEntity<ApiResponse<PageResponse<TicketDto>>> search(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) TicketStatus status,
            @RequestParam(required = false) TicketPriority priority,
            @RequestParam(required = false) Long assignedToId,
            Pageable pageable) {
        try {
            User currentUser = currentUserService.getCurrentUser();
            Page<TicketDto> page = ticketService.searchTickets(keyword, status, priority, assignedToId, pageable, currentUser)
                    .map(SimpleMappers::toTicketDto);
            return ResponseEntity.ok(ApiResponse.success(PageResponse.of(page)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("搜索工单失败: " + e.getMessage()));
        }
    }

    @PostMapping("/advanced-search")
    @Operation(summary = "高级搜索工单", description = "支持多维度条件的高级搜索（带数据权限过滤）")
    @RequirePermission(roles = {RoleConstants.AGENT, RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<PageResponse<TicketDto>>> advancedSearch(
            @RequestBody TicketFilter filter,
            Pageable pageable) {
        try {
            User currentUser = currentUserService.getCurrentUser();
            // 高级搜索使用list(filter, pageable, currentUser)方法
            Page<TicketDto> page = ticketService.list(filter, pageable, currentUser)
                    .map(SimpleMappers::toTicketDto);

            // 管理员空数据特殊提示
            if (currentUser.getRole() == com.example.backend.domain.enums.Role.ADMIN && page.getTotalElements() == 0) {
                log.warn("【管理员空工单列表告警】当前管理员({}), 查询工单列表结果为空，请检查数据或登录态！", currentUser.getUsername());
                return ResponseEntity.ok(ApiResponse.success(
                        "系统管理员: 当前工单列表为空。如果数据库确实有工单且角色为ADMIN，请检查用户账号、数据权限、中间件缓存、数据库等问题。",
                        PageResponse.of(page)
                ));
            }
            return ResponseEntity.ok(ApiResponse.success(PageResponse.of(page)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("高级搜索失败: " + e.getMessage()));
        }
    }

    @GetMapping("/statistics")
    @Operation(summary = "获取工单统计信息", description = "获取工单状态分布、优先级分布等统计信息")
    @RequirePermission(roles = {RoleConstants.AGENT, RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<TicketService.TicketStatistics>> getStatistics() {
        try {
            TicketService.TicketStatistics statistics = ticketService.getTicketStatistics();
            return ResponseEntity.ok(ApiResponse.success(statistics));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取统计信息失败: " + e.getMessage()));
        }
    }

    @GetMapping("/statistics/user/{userId}")
    @Operation(summary = "获取用户工单统计", description = "获取指定用户的工单统计信息")
    @RequirePermission(roles = {RoleConstants.AGENT, RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<TicketService.UserTicketStatistics>> getUserStatistics(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        try {
            TicketService.UserTicketStatistics statistics = ticketService.getUserTicketStatistics(userId);
            return ResponseEntity.ok(ApiResponse.success(statistics));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取用户统计失败: " + e.getMessage()));
        }
    }

    @GetMapping("/trend")
    @Operation(summary = "获取工单趋势分析", description = "获取指定时间范围内的工单趋势数据")
    @RequirePermission(roles = {RoleConstants.AGENT, RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<List<Object[]>>> getTrendAnalysis(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant endDate) {
        try {
            List<Object[]> trendData = ticketService.getTicketTrendAnalysis(startDate, endDate);
            return ResponseEntity.ok(ApiResponse.success(trendData));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取趋势分析失败: " + e.getMessage()));
        }
    }

    @GetMapping("/upcoming-due")
    @Operation(summary = "获取即将到期工单", description = "获取即将到期的工单列表")
    @RequirePermission(roles = {RoleConstants.AGENT, RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<List<TicketDto>>> getUpcomingDueTickets(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant dueTime) {
        try {
            List<TicketDto> tickets = ticketService.getUpcomingDueTickets(dueTime)
                    .stream()
                    .map(SimpleMappers::toTicketDto)
                    .toList();
            return ResponseEntity.ok(ApiResponse.success(tickets));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取即将到期工单失败: " + e.getMessage()));
        }
    }

    @GetMapping("/overdue")
    @Operation(summary = "获取超时工单", description = "获取超时的工单列表")
    @RequirePermission(roles = {RoleConstants.AGENT, RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<PageResponse<TicketDto>>> getOverdueTickets(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant cutoffTime,
            @RequestParam(required = false) TicketStatus status,
            Pageable pageable) {
        try {
            TicketStatus searchStatus = status != null ? status : TicketStatus.OPEN;
            Page<TicketDto> page = ticketService.getOverdueTickets(cutoffTime, searchStatus, pageable)
                    .map(SimpleMappers::toTicketDto);
            return ResponseEntity.ok(ApiResponse.success(PageResponse.of(page)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取超时工单失败: " + e.getMessage()));
        }
    }

    @GetMapping("/sla-compliance")
    @Operation(summary = "获取SLA达成率", description = "获取指定SLA时间内的达成率")
    @RequirePermission(roles = {RoleConstants.AGENT, RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<Double>> getSlaCompliance(
            @RequestParam Integer slaHours) {
        try {
            Double complianceRate = ticketService.getSlaComplianceRate(slaHours);
            return ResponseEntity.ok(ApiResponse.success(complianceRate));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取SLA达成率失败: " + e.getMessage()));
        }
    }

    @GetMapping("/status/{status}")
    @Operation(summary = "根据状态获取工单列表", description = "根据工单状态分页获取工单（带数据权限过滤）")
    public ResponseEntity<ApiResponse<PageResponse<TicketDto>>> listByStatus(
            @Parameter(description = "工单状态") @PathVariable TicketStatus status, 
            Pageable pageable) {
        try {
            User currentUser = currentUserService.getCurrentUser();
            Page<TicketDto> page = ticketService.listByStatus(status, pageable, currentUser)
                    .map(SimpleMappers::toTicketDto);
            return ResponseEntity.ok(ApiResponse.success(PageResponse.of(page)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取工单列表失败: " + e.getMessage()));
        }
    }

    @GetMapping("/user/{userId}")
    @Operation(summary = "获取用户的工单", description = "获取指定用户的工单列表")
    public ResponseEntity<ApiResponse<PageResponse<TicketDto>>> getUserTickets(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            Pageable pageable) {
        try {
            Page<TicketDto> page = ticketService.getUserTickets(userId, pageable).map(SimpleMappers::toTicketDto);
            return ResponseEntity.ok(ApiResponse.success(PageResponse.of(page)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取用户工单失败: " + e.getMessage()));
        }
    }

    @GetMapping("/assigned/{userId}")
    @Operation(summary = "获取分配给用户的工单", description = "获取分配给指定用户的工单列表")
    public ResponseEntity<ApiResponse<PageResponse<TicketDto>>> getAssignedTickets(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            Pageable pageable) {
        try {
            Page<TicketDto> page = ticketService.getAssignedTickets(userId, pageable).map(SimpleMappers::toTicketDto);
            return ResponseEntity.ok(ApiResponse.success(PageResponse.of(page)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取分配工单失败: " + e.getMessage()));
        }
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取工单", description = "根据工单ID获取详细信息（带权限验证）")
    public ResponseEntity<ApiResponse<TicketDto>> getById(
            @Parameter(description = "工单ID") @PathVariable Long id) {
        try {
            User currentUser = currentUserService.getCurrentUser();
            Ticket ticket = ticketService.findByIdWithPermission(id, currentUser)
                    .orElseThrow(() -> new RuntimeException("工单不存在"));
            return ResponseEntity.ok(ApiResponse.success(SimpleMappers.toTicketDto(ticket)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取工单失败: " + e.getMessage()));
        }
    }

    @GetMapping("/number/{ticketNumber}")
    @Operation(summary = "根据工单编号获取工单", description = "根据工单编号获取详细信息（带权限验证）")
    public ResponseEntity<ApiResponse<TicketDto>> getByTicketNumber(
            @Parameter(description = "工单编号") @PathVariable String ticketNumber) {
        try {
            User currentUser = currentUserService.getCurrentUser();
            Ticket ticket = ticketService.findByTicketNumberWithPermission(ticketNumber, currentUser)
                    .orElseThrow(() -> new RuntimeException("工单不存在"));
            return ResponseEntity.ok(ApiResponse.success(SimpleMappers.toTicketDto(ticket)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取工单失败: " + e.getMessage()));
        }
    }

    @PutMapping("/{id}/assign")
    @Operation(summary = "分配工单", description = "将工单分配给指定用户")
    public ResponseEntity<ApiResponse<TicketDto>> assignTicket(
            @Parameter(description = "工单ID") @PathVariable Long id,
            @Valid @RequestBody AssignTicketRequest req) {
        try {
            log.info("开始分配工单: ticketId={}, assigneeId={}", id, req.assigneeId());
            
            // 验证请求参数
            if (req.assigneeId() == null) {
                return ResponseEntity.badRequest().body(ApiResponse.error("指派人ID不能为空", 400));
            }
            
            // 获取指派人
            User assignee = userService.findById(req.assigneeId())
                    .orElseThrow(() -> {
                        log.error("指派人不存在: assigneeId={}", req.assigneeId());
                        return new RuntimeException("用户不存在: ID=" + req.assigneeId());
                    });
            
            log.info("找到指派人: assigneeId={}, username={}, fullName={}", 
                    assignee.getId(), assignee.getUsername(), assignee.getFullName());
            
            // 从当前登录用户获取操作者
            User currentUser = currentUserService.getCurrentUser();
            log.info("当前操作者: userId={}, username={}", currentUser.getId(), currentUser.getUsername());
            
            // 分配工单
            Ticket updated = ticketService.assignTicket(id, assignee, currentUser);
            log.info("工单分配成功: ticketId={}, assigneeId={}", id, req.assigneeId());
            
            return ResponseEntity.ok(ApiResponse.success("工单分配成功", SimpleMappers.toTicketDto(updated)));
        } catch (RuntimeException e) {
            log.error("分配工单失败: ticketId={}, assigneeId={}, error={}", 
                    id, req != null ? req.assigneeId() : "null", e.getMessage(), e);
            return ResponseEntity.badRequest().body(ApiResponse.error("分配工单失败: " + e.getMessage(), 400));
        } catch (Exception e) {
            log.error("分配工单时发生系统异常: ticketId={}, assigneeId={}", 
                    id, req != null ? req.assigneeId() : "null", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("分配工单失败: " + e.getMessage(), 500));
        }
    }

    @PutMapping("/{id}/status")
    @Operation(summary = "更新工单状态", description = "更新工单的状态")
    public ResponseEntity<ApiResponse<TicketDto>> updateStatus(
            @Parameter(description = "工单ID") @PathVariable Long id,
            @Valid @RequestBody UpdateStatusRequest req) {
        try {
            // 从当前登录用户获取操作者
            User currentUser = currentUserService.getCurrentUser();
            Ticket updated = ticketService.updateStatus(id, req.status(), currentUser, req.note());
            return ResponseEntity.ok(ApiResponse.success("工单状态更新成功", SimpleMappers.toTicketDto(updated)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("更新工单状态失败: " + e.getMessage()));
        }
    }

    @PutMapping("/{id}/priority")
    @Operation(summary = "更新工单优先级", description = "更新工单的优先级")
    public ResponseEntity<ApiResponse<TicketDto>> updatePriority(
            @Parameter(description = "工单ID") @PathVariable Long id,
            @Valid @RequestBody UpdatePriorityRequest req) {
        try {
            // 这里应该从当前登录用户获取操作者，暂时使用工单创建者
            Ticket ticket = ticketService.findById(id)
                    .orElseThrow(() -> new RuntimeException("工单不存在"));
            
            Ticket updated = ticketService.updatePriority(id, req.priority(), ticket.getCreatedBy());
            return ResponseEntity.ok(ApiResponse.success("工单优先级更新成功", SimpleMappers.toTicketDto(updated)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("更新工单优先级失败: " + e.getMessage()));
        }
    }



    @GetMapping("/stats/customer/{customerId}")
    @Operation(summary = "获取客户工单统计", description = "获取指定客户的工单统计信息")
    public ResponseEntity<ApiResponse<List<Object[]>>> getCustomerStats(
            @Parameter(description = "客户ID") @PathVariable Long customerId) {
        try {
            List<Object[]> stats = ticketService.getTicketStatsByCustomer(customerId);
            return ResponseEntity.ok(ApiResponse.success(stats));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取客户统计失败: " + e.getMessage()));
        }
    }

    @GetMapping("/stats/assignee/{assigneeId}")
    @Operation(summary = "获取分配者工单统计", description = "获取指定分配者的工单统计信息")
    public ResponseEntity<ApiResponse<List<Object[]>>> getAssigneeStats(
            @Parameter(description = "分配者ID") @PathVariable Long assigneeId) {
        try {
            List<Object[]> stats = ticketService.getTicketStatsByAssignee(assigneeId);
            return ResponseEntity.ok(ApiResponse.success(stats));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取分配者统计失败: " + e.getMessage()));
        }
    }


    @GetMapping("/distribution/status")
    @Operation(summary = "获取工单状态分布", description = "获取工单状态分布统计")
    public ResponseEntity<ApiResponse<List<Object[]>>> getStatusDistribution() {
        try {
            List<Object[]> distribution = ticketService.getTicketStatusDistribution();
            return ResponseEntity.ok(ApiResponse.success(distribution));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取状态分布失败: " + e.getMessage()));
        }
    }

    @GetMapping("/distribution/priority")
    @Operation(summary = "获取工单优先级分布", description = "获取工单优先级分布统计")
    public ResponseEntity<ApiResponse<List<Object[]>>> getPriorityDistribution() {
        try {
            List<Object[]> distribution = ticketService.getTicketPriorityDistribution();
            return ResponseEntity.ok(ApiResponse.success(distribution));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取优先级分布失败: " + e.getMessage()));
        }
    }

    @GetMapping("/metrics/average-resolution-time")
    @Operation(summary = "获取平均解决时间", description = "获取工单平均解决时间（小时）")
    public ResponseEntity<ApiResponse<Double>> getAverageResolutionTime() {
        try {
            Double avgTime = ticketService.getAverageResolutionTimeInHours();
            return ResponseEntity.ok(ApiResponse.success(avgTime));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取平均解决时间失败: " + e.getMessage()));
        }
    }

    @GetMapping("/metrics/sla-compliance")
    @Operation(summary = "获取SLA达成率", description = "获取SLA达成率百分比")
    public ResponseEntity<ApiResponse<Double>> getSlaComplianceRate(
            @RequestParam(defaultValue = "72") Integer slaHours) {
        try {
            Double complianceRate = ticketService.getSlaComplianceRate(slaHours);
            return ResponseEntity.ok(ApiResponse.success(complianceRate));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取SLA达成率失败: " + e.getMessage()));
        }
    }

    // ========== 批量操作API ==========

    // 临时禁用批量指派功能 - 由于BatchOperationService被禁用
    /*
    @PostMapping("/batch/assign")
    @Operation(summary = "批量指派工单", description = "批量将工单指派给指定用户")
    @RequirePermission(roles = {RoleConstants.AGENT, RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<BatchResult>> batchAssignTickets(
            @Valid @RequestBody BatchAssignRequest request) {
        try {
            // 这里应该从当前登录用户获取用户ID，暂时使用固定值
            Long operatorId = 1L; // TODO: 从JWT Token中获取当前用户ID
            
            BatchResult result = batchOperationService.batchAssignTickets(request, operatorId);
            return ResponseEntity.ok(ApiResponse.success("批量指派完成", result));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("批量指派失败: " + e.getMessage()));
        }
    }
    */

    // 临时禁用批量状态更新功能 - 由于BatchOperationService被禁用
    /*
    @PostMapping("/batch/status")
    @Operation(summary = "批量更新工单状态", description = "批量更新工单状态")
    @RequirePermission(roles = {RoleConstants.AGENT, RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<BatchResult>> batchUpdateTicketStatus(
            @Valid @RequestBody BatchStatusRequest request) {
        try {
            // 这里应该从当前登录用户获取用户ID，暂时使用固定值
            Long operatorId = 1L; // TODO: 从JWT Token中获取当前用户ID
            
            BatchResult result = batchOperationService.batchUpdateTicketStatus(request, operatorId);
            return ResponseEntity.ok(ApiResponse.success("批量状态更新完成", result));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("批量状态更新失败: " + e.getMessage()));
        }
    }
    */

    // 临时禁用批量删除功能 - 由于BatchOperationService被禁用
    /*
    @PostMapping("/batch/delete")
    @Operation(summary = "批量删除工单", description = "批量删除工单")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<BatchResult>> batchDeleteTickets(
            @Valid @RequestBody BatchDeleteRequest request) {
        try {
            // 这里应该从当前登录用户获取用户ID，暂时使用固定值
            Long operatorId = 1L; // TODO: 从JWT Token中获取当前用户ID
            
            BatchResult result = batchOperationService.batchDeleteTickets(request, operatorId);
            return ResponseEntity.ok(ApiResponse.success("批量删除完成", result));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("批量删除失败: " + e.getMessage()));
        }
    }
    */
}


